package toy.keli.picmap.util;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.json.JSONTokener;

import java.util.Iterator;

import toy.keli.picmap.model.def;
//android json解析及简单例子  https://www.cnblogs.com/tanqiantot/archive/2012/10/16/3126842.html
public class utilJson {
    static String loop(def json, int level,boolean isArr){
        int i=0;
        String output="",indent="";
        for(String k :json.keys()){
            def v=json.get(k);
            if(i++>0){
                output+= ',';
            }
            if(!k.matches("\\w+")) k='"'+k+'"';
            output+=isArr ? indent: indent+k+":";
            if(v.size()>-1){
                output+=format(v, level);
            }else{
                String vs=v.toString();
                if(vs.indexOf('"')>-1)  vs.replaceAll("\"","\\\"");
                if(! vs.matches("[\\d\\.]+")) vs='"'+vs+'"';
                output+=vs;
            }
        }
        return output;
    }
    static String format(def json,int level){
        String indent="";
        String output="";
        if(json.typeName().equals("array")){
            output="["+loop(json, level+1,true)+indent+"]";
        }
        else if(json.typeName().equals("hash")){
            output="{"+loop(json, level+1,false)+indent+"}";
        }
        return output;
    }

    public static String toString(def t) {
        return format(t,0);
    }




    public static def parsePerson(Object val) throws JSONException {
        def rt = new def();
        if(val instanceof  JSONObject){
            parseObject((JSONObject)val,rt);
        }else if(val instanceof  JSONArray){
            parseArray((JSONArray)val,rt);
        }else {
            return def.valueOf(val);
        }
        return rt;
    }

    public static void parseObject(JSONObject person, def v) throws JSONException {
        for (Iterator<String> it = person.keys(); it.hasNext(); ) {
            String key = it.next();
            Object val = person.get(key);
            v.set(key, parsePerson(val));
        }
    }
    public static void parseArray(JSONArray person, def v) throws JSONException {
       for(int i=0;i<person.length();i++){
        Object val = person.get(i);
        v.push(parsePerson(val));
       }
    }
    public static void parse(String JSON, def v) {
        try {
            JSONTokener jsonParser = new JSONTokener(JSON);
            char c =JSON.charAt(0);
            if (c == '{'){
                parseObject((JSONObject) jsonParser.nextValue(),v);
            }else if(c=='[') {
                parseArray((JSONArray) jsonParser.nextValue(),v);
            }else{
                v.value=new def.zend_val(JSON);
            }
        }catch (Exception e){
            e.printStackTrace();
        }
    }
}
